<template>
  <div>
    <van-nav-bar title="更改密码" left-arrow @click-left="onClickLeft" />
    <div class="pwd" @submit.prevent="handleSubmit">
      <h2>新密码必须与当前密码不同</h2>
      <span>密码</span>
      <van-field
        v-model="form.oldPassword"
        label="旧密码"
        required
        placeholder="请输入旧密码"
        :type="showOldPassword ? 'text' : 'password'"
        :right-icon="showOldPassword ? 'eye-o' : 'closed-eye'"
        @click-right-icon="toggleOldPasswordVisibility"
      />
      <van-field
        v-model="form.newPassword"
        @input="validateNewPassword"
        label="新密码"
        placeholder="请输入新密码"
        :type="showNewPassword ? 'text' : 'password'"
        :right-icon="showNewPassword ? 'eye-o' : 'closed-eye'"
        @click-right-icon="toggleNewPasswordVisibility"
      />
      <p style="color: #8be4b9;">必须至少有6个字符</p>
      <p style="color: #8be4b9; margin-bottom: 1rem;">必须有一个独特的字符，例如@、#、$;等</p>
      <span>确认密码</span>
      <van-field
        v-model="form.confirmPassword"
        label="确认密码"
        required
        placeholder="请确认新密码"
        :type="showConfirmPassword ? 'text' : 'password'"
        :right-icon="showConfirmPassword ? 'eye-o' : 'closed-eye'"
        @click-right-icon="toggleConfirmPasswordVisibility"
      />
      <p v-if="passwordError" class="error">{{ passwordError }}</p>
      <p v-if="confirmError" class="error">{{ confirmError }}</p>
    </div>
    <van-button type="success" @click="handleSubmit" round>提交</van-button>
    <p v-if="successMessage" class="success">{{ successMessage }}</p>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import axios from 'axios';

interface FormData {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const router = useRouter();
const form = ref<FormData>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});
const passwordError = ref<string>('');
const confirmError = ref<string>('');
const successMessage = ref<string>('');
const errorMessage = ref<string>('');
const isSubmitting = ref<boolean>(false);
const route = useRoute();
const userId = route.query.id;

// 控制密码显示状态
const showOldPassword = ref<boolean>(false);
const showNewPassword = ref<boolean>(false);
const showConfirmPassword = ref<boolean>(false);

const onClickLeft = () => {
  window.history.back();
};

const validateNewPassword = () => {
  const oldPass = form.value.oldPassword;
  const newPass = form.value.newPassword;

  if (newPass.length < 6) {
    passwordError.value = '新密码必须至少有6个字符';
    return;
  }

  if (newPass === oldPass) {
    passwordError.value = '新密码不能与旧密码相同';
    return;
  }

  const uniqueChar = newPass.split('').some(char => /[#!@$%^&*]/.test(char));
  if (!uniqueChar) {
    passwordError.value = '新密码必须包含一个独特的字符，例如@、#、$;等';
    return;
  }

  passwordError.value = '';
};

const handleSubmit = async () => {
  try {
    isSubmitting.value = true;
    passwordError.value = '';
    confirmError.value = '';
    successMessage.value = '';
    errorMessage.value = '';

    if (!userId) {
      errorMessage.value = '用户ID无效，请检查';
      showToast({ message: errorMessage.value, type: 'fail' });
      return;
    }

    if (form.value.newPassword.length < 6) {
      passwordError.value = '新密码必须至少有6个字符';
      return;
    }

    if (form.value.newPassword !== form.value.confirmPassword) {
      confirmError.value = '两次输入的新密码不一致';
      return;
    }

    const response = await axios.post(`http://localhost:3000/change-password/${userId}`, {
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword,
    });

    if (response.data.success) {
      successMessage.value = '密码修改成功！';
      showToast({ message: '密码修改成功', type: 'success' });
      setTimeout(() => router.push('/'), 1500);
    } else {
      errorMessage.value = response.data.message || '密码修改失败，请重试';
      showToast({ message: errorMessage.value, type: 'fail' });
    }
  } catch (error) {
    errorMessage.value = '发生错误，请稍后重试';
    showToast({ message: errorMessage.value, type: 'fail' });
    console.error(error);
  } finally {
    isSubmitting.value = false;
  }
};

// 切换旧密码显示状态
const toggleOldPasswordVisibility = () => {
  showOldPassword.value = !showOldPassword.value;
};

// 切换新密码显示状态
const toggleNewPasswordVisibility = () => {
  showNewPassword.value = !showNewPassword.value;
};

// 切换确认密码显示状态
const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};
</script>

<style scoped>
.pwd {
  margin-left: 2rem;
  margin-top: 2rem;
}

h2 {
  margin-top: 3rem;
  margin-bottom: 3rem;
}

span {
  font-size: 0.8rem;
  font-weight: 200;
}

.van-field {
  width: 90%;
  background-color: #f6f8fe;
  margin-top: 1rem;
  margin-bottom: 1rem;
}

.van-button {
  width: 90%;
  margin-left: 1.5rem;
  margin-top: 23rem;
  margin-bottom: 2rem;
}

.van-nav-bar {
  position: fixed;
  top: 0;
  z-index: 999;
  width: 100%;
}
</style>